//
import { RequestBodyParams } from './RequestBody/RequestBodyParams'
import { ESApp } from '@extscreen/es3-vue'
import { RequestDevelopParams } from './RequestBody/RequestDevelopParams'
import { ESDevelop, ESDevice, ESLog, ESLogLevel, ESRuntime } from '@extscreen/es3-core'
import { RequestDeviceParams } from './RequestBody/RequestDeviceParams'
import { RequestBaseParams } from './RequestBody/RequestBaseParams'
import { RequestUserParams } from './RequestBody/RequestUserParams'
import { RequestRuntimeParams } from './RequestBody/RequestRuntimeParams'
import { ES } from '@extscreen/es3-core/dist/src/es/ES'
import { RequestData } from './RequestBody/RequestData'
import BuildConfig from '../../build/BuildConfig'
import { RequestManagerKey } from '../UseApi'

export interface RequestManager {
  install(app: ESApp): void

  init(...params: any[]): Promise<any>

  post(url: string, data: RequestData, header?: Object): Promise<any>

  get(url: string, data: RequestData): Promise<any>

  updateUserParams(userInfo: RequestUserParams): void
  getParams(): any
}

//
const TAG = 'RequestManager'
export function createRequestManager(): RequestManager {
  let requestParams: RequestBodyParams
  let es: ES
  let develop: ESDevelop
  let device: ESDevice
  let runtime: ESRuntime
  let log: ESLog

  function init(...params: any[]): Promise<any> {
    es = params[0]
    develop = params[1]
    device = params[2]
    runtime = params[3]
    log = params[4]
    localStorage = params[5]

    const developParams = initDeveloperRequestParams()
    const deviceParams = initDeviceRequestParams()
    const baseParams = initParamsRequestParams()
    const userParams = initUserRequestParams()
    const runtimeParams = initRuntimeBaseParams()

    console.log('deviceParams >>', deviceParams)

    //todo 封装公共参数
    // requestParams = {
    //   developer: developParams,
    //   device: deviceParams,
    //   param: baseParams,
    //   user: userParams,
    //   runtime: runtimeParams,
    // }

    // requestParams = {
    // developer: developParams,
    // device: deviceParams,
    // param: baseParams,
    // user: userParams,
    // runtime: runtimeParams,
    // }
    return Promise.resolve()
  }

  function initDeveloperRequestParams(): RequestDevelopParams {
    return {
      packagename: BuildConfig.packageName,
      vercode: develop.getVersionCode(),
      vername: develop.getVersionName(),
      dynamicCode: 1
    }
  }

  function initDeviceRequestParams(): RequestDeviceParams {
    let mac = device.getDeviceEthMac()
    let es_mac = device.getDeviceEthMac()
    if (!mac) {
      mac = device.getDeviceWifiMac()
    }
    let wifi_mac = device.getDeviceWifiMac()
    mac = mac.replace(/:/g, '').toLowerCase()
    if (es_mac) {
      es_mac = es_mac.replace(/:/g, '').toLowerCase()
    }
    if (wifi_mac) {
      wifi_mac = wifi_mac.replace(/:/g, '').toLowerCase()
    }
    return {
      brand: device.getBuildBrand(),
      clientType: runtime.getRuntimeDeviceType() ?? '',
      dnum: runtime.getRuntimeDeviceId() ?? '',
      mac: mac,
      esMac: es_mac,
      esWifiMac: wifi_mac,
      manufacturer: device.getBuildManufacturer(),
      model: device.getBuildModel(),
      deviceVersion: device.getBuildVersionRelease()
    }
  }

  function initParamsRequestParams(): RequestBaseParams {
    return {
      // channelCode: develop.getChannel(),
      channelCode: 'CHANGHONG',
      versionCode: develop.getVersionCode()
    }
  }

  function initUserRequestParams(): RequestUserParams {
    return {
      userId: '',
      userToken: '',
      nickname: ''
    }
  }

  function updateUserParams(userInfo: RequestUserParams): void {
   
  }
  function getParams() {
  }

  function initRuntimeBaseParams(): RequestRuntimeParams {
    return {
      sdkVersion: es.getESSDKVersionCode(),
      sdkCID: runtime.getRuntimeDeviceId() ?? '',
      runtimeID: '',
      hostPackageName: develop.getPackageName(),
      hostVersion: develop.getVersionCode(),
      hostChannel: develop.getChannel(),
      snCode: ''
    }
  }

  function post<T>(url: string, data: RequestData, header = {}): Promise<T> {
    return request('POST', url, data, header)
  }

  function get<T>(url: string, params: RequestData): Promise<T> {
    return new Promise(async (resolve, reject) => {
      const requestUrl = url + getQueryString(params)
      console.log('123  requestUrl >>>>', url)

      let headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      }

      let token = await localStorage.getString('user_token', '')
      if (token) {
        headers['Authorization'] = token
      }

      fetch(requestUrl, {
        method: 'GET',
        headers: headers
      })
        .then((response) => {
          return response.json()
        })
        .then((responseJson) => {
          if (log.isLoggable(ESLogLevel.DEBUG)) {
            log.d(TAG, '################### RESPONSE START ########################')
            log.d(TAG, 'response:' + JSON.stringify(responseJson))
            console.log('%c RESPONSE <--', 'color: cyan; font-size: 18px', responseJson)
            console.log(
              '%c RESPONSE <--',
              'color: cyan; font-size: 18px',
              JSON.stringify(responseJson)
            )
            log.d(TAG, '################### RESPONSE END   ########################')
          }
          if (responseJson.code === 200 || responseJson.returncode == '0') {
            resolve(responseJson)
          } else {
            reject({
              code: responseJson.code,
              message: responseJson.message
            })
          }
        })
        .catch((err) => {
          reject({
            code: '-1',
            message: '发生错误，请稍后重试！'
          })
        })
    })
  }

  function request<T>(
    method: string,
    url: string,
    data: RequestData,
    header: Object = {}
  ): Promise<T> {
    return new Promise(async (resolve, reject) => {
      const requestUrl = url
      let apiName = requestUrl.split('aimxd-webapi-online/')[1]
        ? requestUrl.split('aimxd-webapi-online/')[1]
        : requestUrl
      if (log.isLoggable(ESLogLevel.DEBUG)) {
        // log.d(TAG, '-----------request-------------->>>>requestUrl:' + requestUrl)
        console.log(
          '%c REQUEST URL: ' + apiName,
          'color: #fff; font-size: 18px; font-weight: bold;'
        )
      }
 
      let requestData = { ...data }

      let headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      }

      let token = await localStorage.getString('user_token', '')
      if (token) {
        headers['Authorization'] = token
      }
      if (Object.keys(header).length) {
        headers = Object.assign(headers, header)
        if (log.isLoggable(ESLogLevel.DEBUG)) {
          log.d(TAG, 'requestHeader:' + JSON.stringify(headers))
        }
      }

      fetch(requestUrl, {
        method: method,
        headers: headers,
        body: JSON.stringify(requestData)
      })
        .then((response) => {
          return response.json()
        })
        .then((responseJson) => {
        })
        .catch((error) => {
          console.log('%c ERROR <--', 'color: red; font-size: 18px', error)
          reject({
            code: '-1',
            message: '发生错误，请稍后重试！' + error
          })
        })
    })
  }

  function getQueryString(params: Record<string, any>) {
    let queryString = ''
    for (const key in params) {
      if (params.hasOwnProperty(key)) {
        if (queryString) {
          queryString += `&${key}=${params[key]}`
        } else {
          queryString = `?${key}=${params[key]}`
        }
      }
    }
    return queryString
  }

  return {
    install: function (app: ESApp) {
      const instance = this
      app.provide(RequestManagerKey, instance)
    },
    init,
    post,
    get,
    updateUserParams,
    getParams
  }
}
